package com.estronger.shopmanage.adapter;

import android.Manifest;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.gaodemap.LocationActivity;
import com.estronger.shopmanage.ui.install.BuildActivity;
import com.estronger.shopmanage.ui.install.BuildDetailActivity;
import com.estronger.shopmanage.ui.install.BuildRegisterActivity;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.ui.install.TestimonyActivity;
import com.estronger.shopmanage.base.BaseHolder;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B30BuildList.BuildListData;
import com.estronger.shopmanage.bean.BeanBase;
import com.estronger.shopmanage.fragment.install.BuildBaseFragment;
import com.estronger.shopmanage.fragment.FragmentFactory;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.AppDialog;
import com.estronger.shopmanage.view.textview.CYTextView;
import com.google.gson.Gson;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.systemcodes.SystemCodes;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.List;

public class BuildListAdapter extends DefaultAdapter<BuildListData> {

    private BuildActivity mContext;
    private Gson gson;
    protected static final short READY_RECEIVE = 0;
    protected static final short READY_CONTACT = 1;
    protected static final short READY_ARRIVE = 2;
    protected static final short READY_SAY_YES = 5;
    protected static final short FINISH = 6;
    private Dialog dialog;
    private View needDeleteView = null;
    private String needDeleteId = "";
    private BuildBaseFragment fragment;
    private boolean isAll;
    boolean needResult = true;
    private boolean ifFinishCanUpdateAttaOnly = false;//是否支持仅上传图片不完工，默认不支持

    public BuildListAdapter(BuildActivity mContext, List<BuildListData> datas,
                            Gson gson, BuildBaseFragment fragment, boolean isAll) {
        super(datas);
        this.mContext = mContext;
        this.gson = gson;
        this.fragment = fragment;
        this.isAll = isAll;
        ifFinishCanUpdateAttaOnly = SystemCodes.getInstance().getDSM_IfFinishCanUpdateAttaOnly()==1 ? true : false;
    }

    @Override
    protected BaseHolder<BuildListData> getHolder() {
        return new BuildListHoder();
    }

    // 当删除一个条目的动画执行完之后调用
    protected void deleteItem(String dlvid) {
        if (TextUtils.isEmpty(dlvid)) {
            return;
        }
        for (int i = 0; i < datas.size(); i++) {
            if ((datas.get(i).dlvid).equals(dlvid)) {
                datas.remove(datas.get(i));
                notifyDataSetChanged();
            }
        }
    }

    /**
     * @author Administrator 一个Adapter配一个Hoder的意思吧
     */
    class BuildListHoder extends BaseHolder<BuildListData> implements
            OnClickListener {
        private FrameLayout fl_build_item;
        private TextView item_name, item_phone, appointment, appointment_time,
                location;
        private ImageView state, call, sms;
        private LinearLayout item_contact, item_castomer, item_finish,
                item_receive, item_bottom, ll_remark;
        private RelativeLayout rl_intall_upload, rl_install_finish;
        private CYTextView tv_remark;//备注说明
        private View item_line;

        /**
         * 主要是处理一个安装任务条目里面的各种点击事件 比如R.id.build_send_sms是点击了条目上的发短信小图标的处理
         */
        @Override
        public void onClick(final View v) {
            String dlvid = getFTag(fl_build_item);
            Intent intent;
            switch (v.getId()) {
                case R.id.build_send_sms:
                    String number1 = item_phone.getText().toString();
                    if (mContext.isRightNumber(number1)) {
                        Uri uri = Uri.parse("smsto:" + number1);
                        intent = new Intent(Intent.ACTION_SENDTO, uri);
                        mContext.startActivity(intent);
                    }
                    break;
                case R.id.build_phone_call:// 点击了送货条目上的电话小图标
                case R.id.build_item_contact:// 点击了送货条目上的与客户确认预约
                    String number = item_phone.getText().toString();
                    if (mContext.isRightNumber(number)) {
                        dialog = AppDialog.createDialog(mContext,
                                this.data.cstname, number, this, dlvid);
                        if (v.getId() == R.id.build_item_contact) {
                            needResult = true;
                        } else {
                            needResult = false;
                        }
                        dialog.show();
                    }
                    break;
                    //客户证言登记
                case R.id.build_item_castomer:
                    intent = new Intent(mContext, TestimonyActivity.class);
                    intent.putExtra("dlvid", dlvid);
                    mContext.startActivityForResult(intent,
                            BuildActivity.REFLESH_DATA);
                    break;
                //仅上传图片和录音
                case R.id.rl_intall_upload:
                    intent = new Intent(mContext, BuildRegisterActivity.class);
                    intent.putExtra("dlvid", dlvid);
                    intent.putExtra("pageType", 1);
                    mContext.startActivityForResult(intent,
                            BuildActivity.REFLESH_DATA);
                    break;
                //保存且完工登记
                case R.id.rl_install_finish:
                    intent = new Intent(mContext, BuildRegisterActivity.class);
                    intent.putExtra("dlvid", dlvid);
                    intent.putExtra("pageType", 0);
                    mContext.startActivityForResult(intent,
                        BuildActivity.REFLESH_DATA);
                    break;
                //领取
                case R.id.build_item_receive:
                    RequestParams params = new RequestParams();
                    params.addBodyParameter("sf_action", "istaccepttask");//安装任务领取
                    params.addBodyParameter("usercode", MyApplication.getUserCode());
                    params.addBodyParameter("dlvid", dlvid);
                    netManager.connectWork(params, NetManager.BUILD_GET_TASK);
                    mContext.setProgresVisible(true);
                    View v2 = (View) ((View) (v.getParent())).getParent();
                    needDeleteView = (View) v2.getParent();
                    needDeleteId = dlvid;
                    break;
                case R.id.build_item_layout:
                    // Toast.show(mContext, "click", 0).show();
                    String complesh = getFTag(item_finish);
                    boolean isComplesh = false,
                            iftestimony = false;
                    if (complesh.equals("1")) {
                        isComplesh = true;
                        iftestimony = true;
                    }
                    if (complesh.equals("2")) {
                        isComplesh = true;
                    }
                    intent = new Intent(mContext, BuildDetailActivity.class);
                    intent.putExtra("dlvid", dlvid);
                    intent.putExtra("isComplesh", isComplesh);
                    intent.putExtra("iftestimony", iftestimony);
                    mContext.startActivityForResult(intent,
                            BuildActivity.REFLESH_DATA);
                    break;
                case R.id.ok:
                    String number2 = item_phone.getText().toString();
                    BuildActivity.send_deliv_id = dlvid;
                    intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
                            + number2));
                    if (needResult) {
                        BuildActivity.CALL_RESULT = Integer.valueOf(dlvid);
                        mContext.startActivityForResult(intent,
                                BuildActivity.SEND_CALL);
                    } else {
                        mContext.startActivity(intent);
                    }
                    dialog.dismiss();
                    break;
                case R.id.build_item_location:
                    PermissionUtils.getInstance().requestPromisssions(mContext, new PermissionUtils.AcceptListener() {
                        @Override
                        public void grante() {
                            TextView tv = (TextView) v;
                            String add = tv.getText().toString().trim();
                            if (!add.equals("")) {
                                Intent intent = new Intent(mContext, LocationActivity.class);
                                intent.putExtra("latitude", "");
                                intent.putExtra("location", add);
                                intent.putExtra("longtitude", "");
                                mContext.startActivityForResult(intent, 8889);
                            } else {
                                Toast.show(mContext, "安装客户地址为空", 2000);
                            }
                        }

                        @Override
                        public void denial(Permission permission) {

                        }

                        @Override
                        public void fail() {

                        }
                    },Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION);
                    break;
            }
        }

        private String getFTag(View view) {
            try{
               String ftag = (String) view.getTag();
               if (ftag != null) return ftag.toString();
               else return "";
            }catch (Exception e){
                return "";
            }
        }

        /**
         * 当前activity所有联网成功的回调
         *
         * @params code 各个接口返回的唯一识别码，用来判断是哪个接口成功返回
         * @params result 网络请求成功返回的数据
         */
        @Override
        protected void onNetSuccess(int code, String result) {
            if (NetManager.BUILD_GET_TASK == code) {
                BeanBase task = gson.fromJson(result, BeanBase.class);
                if (mContext != null) {
                    mContext.getTaskResult(task.success);
                }
                if (task.success && needDeleteView != null) {
                    removeAnim(needDeleteView.getHeight(), needDeleteView);
                }
            }
            mContext.setProgresVisible(false);
        }

        @Override
        protected void onNetErorr(int code, String result) {
            mContext.setProgresVisible(false);
            // Toast.show(mContext, "网络异常", 0).show();
        }

        /**
         * 初始化一个安装条目中的内容
         */
        @Override
        public View initView() {
            View view = View.inflate(mContext, R.layout.build_item, null);
            fl_build_item = view.findViewById(R.id.fl_build_item);
            item_name = (TextView) view.findViewById(R.id.build_item_name);
            item_phone = (TextView) view.findViewById(R.id.build_item_phone);
            location = (TextView) view.findViewById(R.id.build_item_location);
            appointment = (TextView) view.findViewById(R.id.appointment);
            appointment_time = (TextView) view
                    .findViewById(R.id.appointment_time);

            state = (ImageView) view.findViewById(R.id.build_item_state);
            item_contact = (LinearLayout) view
                    .findViewById(R.id.build_item_contact);
            item_castomer = (LinearLayout) view
                    .findViewById(R.id.build_item_castomer);
            item_finish = (LinearLayout) view
                    .findViewById(R.id.build_item_finish);
            item_receive = (LinearLayout) view
                    .findViewById(R.id.build_item_receive);
            ll_remark = (LinearLayout) view.findViewById(R.id.ll_remark);
            tv_remark = (CYTextView) view.findViewById(R.id.tv_remark);

            item_bottom = (LinearLayout) view
                    .findViewById(R.id.build_item_bottom);
            item_line = view.findViewById(R.id.build_item_line);

            rl_intall_upload = (RelativeLayout) view
                    .findViewById(R.id.rl_intall_upload);
            rl_install_finish = (RelativeLayout) view
                    .findViewById(R.id.rl_install_finish);

            call = (ImageView) view.findViewById(R.id.build_phone_call);
            sms = (ImageView) view.findViewById(R.id.build_send_sms);

            if (isAll) {
                item_bottom.setVisibility(View.GONE);
                item_line.setVisibility(View.GONE);
            }

            call.setOnClickListener(this);
            sms.setOnClickListener(this);
            item_phone.setOnClickListener(this);
            location.setOnClickListener(this);
            view.setOnClickListener(this);
            return view;
        }

        @Override
        public void refreshView(BuildListData data) {
            if (TextUtils.isEmpty(data.buildname)) {
                item_name.setText(data.cstname);
            } else {
                item_name.setText(data.buildname + "-" + data.cstname);
            }
            item_phone.setText(data.cstmobile);
            location.setText(data.address);
            appointment.setText("预约时间：" + data.getPidate());
            appointment_time.setText(TimeUtils.chaZhi(data.pidate));
            if (TextUtils.isEmpty(data.remark)) {
                ll_remark.setVisibility(View.GONE);
            }else {
                ll_remark.setVisibility(View.VISIBLE);
                tv_remark.setText(data.remark);//
                tv_remark.setNeatFormat();
            }
            fl_build_item.setTag(data.dlvid);

            item_finish.setTag(data.dlvid);

            item_contact.setOnClickListener(this);
            item_castomer.setOnClickListener(this);
            item_receive.setOnClickListener(this);
            rl_intall_upload.setOnClickListener(this);
            rl_install_finish.setOnClickListener(this);
            if (!TextUtils.isEmpty(data.status)) {
                int code = Integer.valueOf(data.status);
                switch (code) {
                    case READY_RECEIVE:
                        state.setImageResource(R.drawable.state_receive_icon);
                        break;
                    case READY_CONTACT:
                        state.setImageResource(R.drawable.state_appointment_icon);
                        item_contact.setVisibility(View.VISIBLE);
                        item_receive.setVisibility(View.GONE);
                        break;
                    case READY_ARRIVE:
                        state.setImageResource(R.drawable.state_install_icon);
                        item_castomer.setVisibility(View.GONE);
                        item_receive.setVisibility(View.GONE);
                        if(ifFinishCanUpdateAttaOnly) {
                            rl_intall_upload.setVisibility(View.VISIBLE);
                        }else {
                            rl_intall_upload.setVisibility(View.GONE);
                        }
                        item_finish.setVisibility(View.VISIBLE);
                        break;
                    case READY_SAY_YES:
                        state.setImageResource(R.drawable.state_testimony_icon);
                        item_castomer.setVisibility(View.VISIBLE);
                        item_finish.setVisibility(View.GONE);
                        item_receive.setVisibility(View.GONE);
                        break;
                }
            }

            if ("1".equals(data.iststatus) && "1".equals(data.iftestimony)) {
                state.setImageResource(R.drawable.state_complete_icon);
                item_finish.setTag("1");
            }

            if ("1".equals(data.iststatus) && "0".equals(data.iftestimony)) {
                state.setImageResource(R.drawable.state_testimony_icon);
                item_castomer.setVisibility(View.VISIBLE);
                item_finish.setVisibility(View.GONE);
                item_receive.setVisibility(View.GONE);
                item_finish.setTag("2");
            }
        }

        private void removeAnim(int startHeight, final View v) {
            if (v == null)
                return;
            ValueAnimator animator = ValueAnimator.ofInt(startHeight, 0);
            animator.addUpdateListener(new AnimatorUpdateListener() {

                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    int value = (Integer) animation.getAnimatedValue();
                    LayoutParams params = v.getLayoutParams();
                    params.height = value;
                    // v.getLayoutParams
                    v.setLayoutParams(params);

                }
            });
            animator.addListener(new AnimatorListener() {
                @Override
                public void onAnimationStart(Animator arg0) {
                }

                @Override
                public void onAnimationRepeat(Animator arg0) {
                }

                @Override
                public void onAnimationEnd(Animator arg0) {
                    deleteItem(needDeleteId);
                    FragmentFactory.createBuildFragment(
                            mContext.getCurrPosition()).connect(
                            fragment.gettype());
                }

                @Override
                public void onAnimationCancel(Animator arg0) {

                }
            });
            animator.setDuration(500);
            animator.start();
        }
    }
}
